<template>
  <div class="app-container">
    <!--操作按钮-->
    <div style="padding-bottom: 30px;" class="operation_container">
      <ul>
        <li><el-button size="mini" @click="handleCancel">返回</el-button></li>
        <li><el-button size="mini" type="primary" @click="handleSubmit">保存</el-button></li>
      </ul>
    </div>
    <!--折叠面板-->
    <el-collapse v-model="activeNames" @change="handleChange">
      <el-collapse-item name="basicInfo">
        <template slot="title">
          <span>基本信息</span>
          <i class="header-icon el-icon-info" />
        </template>
        <el-form ref="form" :model="data" :rules="rules" :inline="true" size="mini" label-width="125px">
          <el-row :gutter="24" class="form-item-group">
            <el-col :span="6">
              <el-form-item label="运单号：">
                <el-input v-model="data.freightOrderNo" disabled placeholder="系统自动生成" />
              </el-form-item>
            </el-col>


            <el-col :span="6">
              <el-form-item label="公里数：">
                <el-input v-model="data.miles" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="form-item-group">
            <el-col :span="6">
              <el-form-item label="托运人：" prop="customerName">
                <el-input v-model="data.customerName" class="filter-item">
                  <i slot="suffix" class="el-input__icon el-icon-search" @click="openFromSelector" />
                </el-input>
                <basic-spu-selector :visible.sync="fromSelectorVisible" @selected="handleFromSelected" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="托运人电话：" prop="customerPhone">
                <el-input v-model="data.customerPhone" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="托运人地址：" prop="customerAddress">
                <el-input v-model="data.customerAddress" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="送达天数：">
                <el-input v-model="data.estDeliveryDays" type="number" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="form-item-group">
            <el-col :span="6">
              <el-form-item label="收货人：" prop="consigneeName">
                <el-input ref="consigneeName" v-model="data.consigneeName" class="filter-item">
                  <i slot="suffix" class="el-input__icon el-icon-search" @click="openToSelector" />
                </el-input>
                <customer-consignee-selector :visible.sync="toSelectorVisible" @selected="handleToSelected" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收货人电话：" prop="consigneePhone">
                <el-input v-model="data.consigneePhone" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收货人地址：" prop="consigneeAddress">
                <el-input v-model="data.consigneeAddress" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="要求发货时间：" prop="carrierTime">
                <el-date-picker
                  v-model="data.carrierTime"
                  type="date"
                  placeholder="选择日期"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="form-item-group">
            <el-col :span="6">
              <el-form-item label="结算方式：">
                <el-select v-model="data.paymentType" filterable clearable>
                  <el-option v-for="item in selects.paymentTypeList" :key="item.key" :label="item.label" :value="item.key" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="服务类型：" size="mini">
                <el-select v-model="data.serviceType" filterable clearable>
                  <el-option v-for="item in selects.freightServiceTypeList" :key="item.key" :label="item.label" :value="item.key" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="运单类型：" size="mini">
                <el-radio-group v-model="data.freightOrderTypeNo">
                  <el-radio v-for="item in selects.freightOrderTypeList" :key="item.key" :label="item.key">{{ item.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>


           <el-col :span="6">
             <el-form-item label="最大承重：">
               <el-input v-model="data.maxWeight" type="number"  />
             </el-form-item>
           </el-col>
           <el-col :span="6">
             <el-form-item label="最大容积：">
               <el-input v-model="data.maxVol" type="number"  />
             </el-form-item>
           </el-col>
          </el-row>
        </el-form>
      </el-collapse-item>

    </el-collapse>
  </div>
</template>

<script>

import appConstant from '@/constant/AppConstant'


import BasicSpuSelector from '@/views/goods/basicSpu/BasicSpuSelector'

export default {

  components: {
    BasicSpuSelector
  },
  filters: {
    categoryFilter(item) {
      const values = appConstant.categoryList.filter(value => value.key === item)
      if (values && values.length > 0) {
        return values[0].label
      } else {
        return ''
      }
    }
  },
  data() {
    return {
      activeNames: [
        'basicInfo',
        'itemInfo'],
      selects: {
        ynTypeList: appConstant.ynTypeList,
        freightServiceTypeList: appConstant.freightServiceTypeList,
        freightOrderTypeList: appConstant.freightOrderTypeList,
        materialTransUnitList: appConstant.materialTransUnitList,
        paymentTypeList: appConstant.paymentTypeList,
        settledBasedOnList: appConstant.settledBasedOnList,
        categoryList: appConstant.categoryList,
        packingList: appConstant.packingList,
        paymentcompanyList: appConstant.paymentcompanyList,
        weightMeasUnitList: appConstant.weightMeasUnitList,
        vehicleModelSelectList: appConstant.vehicleModelList,
        vehicleModelLengthSelectList: appConstant.vehicleModelLengthList,
        locationList: []
      },
      operation: undefined,
      data: {
        isValid: appConstant.Y,
        itemList: [],
        departureIdList: [],
        destinationIdList: [],
        vehicleModelSelectList: [],
        vehicleModelLengthSelectList: [],
        miles: undefined,
        maxWeight: undefined,
        maxVol: undefined,
        customerName: undefined,
        customerPhone: undefined,
        customerAddress: undefined,
        consigneeName: undefined,
        consigneePhone: undefined,
        consigneeAddress: undefined,
        carrierTime: undefined
      },
      // 校验规则的名称必须和校验字段的名称一致
      rules: {
        departureIdList: [{ required: true, message: '_', trigger: 'change' }],
        destinationIdList: [{ required: true, message: '_', trigger: 'change' }],
        customerName: [{ required: true, message: '_', trigger: 'blur' }],
        customerPhone: [{ required: true, message: '_', trigger: 'blur' }],
        customerAddress: [{ required: true, message: '_', trigger: 'blur' }],
        consigneeName: [{ required: true, message: '_', trigger: 'blur' }],
        consigneePhone: [{ required: true, message: '_', trigger: 'blur' }],
        consigneeAddress: [{ required: true, message: '_', trigger: 'blur' }],
        carrierTime: [{ required: true, message: '_', trigger: 'change' }]
      },
      materialSelectorVisible: false,
      fromSelectorVisible: false,
      toSelectorVisible: false,
      orgSelectorVisible: false,
      vehicleModelSelectorVisible: false,
      itemDisplay: false,
      itemData: {
        cargoFreightName: undefined,
        cargoFreightNo: undefined,
        weightMeasUnit: undefined,
        weight: 0,
        unitPrice: 0,
        cargoValue: 0,
        insuranceFeeRate: 0,
        insuranceExpense: 0,
        countPrice: 0,
        countCarriage: 0,
        amountExpense: 0
      },
      itemRules: {
        cargoFreightName: [{ required: true, message: '_', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.initForm()
    this.loadSelects()
  },
  methods: {
    initForm() {
      const id = this.$route.params.id
      if (id) {
        this.operation = 'edit'
        FreightOrderApi.get(id).then(response => {
          this.data = response.data
          // 将字符串转为数组
          if (this.data.departure) {
            this.data.departureIdList = this.data.departure.split(',')
          }
          if (this.data.destination) {
            this.data.destinationIdList = this.data.destination.split(',')
          }
        })
      } else {
        this.operation = 'add'
        CustomerApi.getByUser().then(response => {
        //  this.data = response.data
          this.data.customerNo = response.data.id
          this.data.customerName = response.data.customerName
          this.data.customerPhone = response.data.phone
          this.data.customerAddress = response.data.address
          this.data.paymentType = response.data.paymentType
          this.data.serviceType = response.data.serviceType
          this.data.departCity = response.data.areaDesc
          if (this.data.departCity) {
            this.data.departureIdList = this.data.departCity.split(',')
          }
        })
      }
    },
    loadSelects() {
      LocationApi.list().then(response => {
        this.selects.locationList = TreeUtils.list2Tree(response.data)
      })
    },
    handleSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 将数组转为字符串
          if (this.data.departureIdList) {
            this.data.departure = this.data.departureIdList.join(',')
          }
          if (this.data.destinationIdList) {
            this.data.destination = this.data.destinationIdList.join(',')
          }
          if (this.operation === 'add') {
            FreightOrderApi.addAll(this.data).then(response => {
              this.$message.success('新增成功！')
              this.$router.go(-1)
            })
          } else if (this.operation === 'edit') {
            FreightOrderApi.edit(this.data).then(response => {
              this.$message.success('编辑成功！')
              this.$router.go(-1)
            })
          }
        }
      })
    },
    handleCancel() {
      this.$router.go(-1)
    },
    handleChange(val) {
      console.log(val)
    },
    openMaterialSelector() {
      this.materialSelectorVisible = true
    },
    handleVehicleModelChange() {
      this.data.maxWeight = undefined
      this.data.maxVol = undefined
      const params = {
        vehicleModelNo: this.data.ftlRequestVehicleType,
        vehicleLength: this.data.ftlRequestVehicleLength
      }
      VehicleModelApi.list(params).then(response => {
        if (response.data[0] != null) {
          this.data.maxWeight = response.data[0].carryCapacity
          this.data.maxVol = response.data[0].volume
        }
      })
    },
    handleMaterialSelected(obj) {
      this.itemData = {
        ...this.itemData,
        cargoFreightName: obj.materialName,
        cargoFreightType: obj.categoryId,
        unitPrice: obj.unitPrice,
        cargoFreightNo: obj.id,
        unitWeight: obj.unitWeight,
        weightMeasUnit: obj.weightMeasUnit
      }
    },
    openFromSelector() {
      this.fromSelectorVisible = true
    },
    handleFromSelected(obj) {
      this.data.customerNo = obj.id
      this.data.customerName = obj.customerName
      this.data.customerPhone = obj.phone
      this.data.customerAddress = obj.address
      this.data.departure = obj.areaDesc
      if (this.data.departure) {
        this.data.departureIdList = this.data.departure.split(',')
      }
    },
    openToSelector() {
      this.toSelectorVisible = true
    },
    handleToSelected(obj) {
      this.data.consigneeName = obj.consigneeName
      this.data.consigneeNo = obj.id
      this.data.consigneePhone = obj.linkManMobile
      this.data.consigneeAddress = obj.consigneeAddress
      this.data.destination = obj.areaDesc
      if (this.data.destination) {
        this.data.destinationIdList = this.data.destination.split(',')
        const params = {
          startLocation: this.data.departureIdList.join(','),
          endLocation: this.data.destinationIdList.join(',')
        }
        TransitRouteApi.list(params).then(response => {
          if (response.data.length > 0) {
            // 设置里程
            this.data.miles = response.data[0].milometer
            this.data.estDeliveryDays = response.data[0].estDeliveryDays
          }
        })
      }
    },
    handleItemFormDisplay() {
      var that = this
      this.itemDisplay = !this.itemDisplay
      this.itemData = {}
      const params = {
        dptrAreaCd: this.data.departureIdList.join(','),
        arrAreaCd: this.data.destinationIdList.join(','),
        custCd: '*'
      }
      RoutePriceNewApi.list(params).then(response => {
        if (response.data.length > 0) {
          // 设置单价
          that.itemData.countPrice = response.data[0].basicAmt
          // that.$set(that.itemData, countPrice, response.data[0].basicAmt);
        }
      })
    },
    handleItemAdd() {
      if (this.itemData.cargoFreightName) {
        // 解决itemList中所有item的内存地址一样的问题
        const data = {
          ...this.itemData
        }
        // 校验必填字段
        this.$refs['itemForm'].validate((valid) => {
          if (valid) {
            this.data.itemList.push(data)
            this.itemData = {
            }
            this.$message.success('添加成功！')
          }
        })
      } else {
        this.$message.warning('请选择物料！')
      }
    },
    handleItemEdit(data) {
      this.itemDisplay = true
      this.itemData = {
        ...data
      }
      this.handleItemDelete(data)
    },
    handleItemDelete(data) {
      const index = this.data.itemList.indexOf(data)
      this.data.itemList.splice(index, 1)
    },
    handleCalShipmentExpense() {
      if (this.itemData.countPrice && this.itemData.shipByPackOrqty) {
        if (this.itemData.shipByPackOrqty === 'weight') {
          if (this.itemData.weight) {
            if (this.itemData.weight > this.data.maxWeight) {
               this.$message.warning('超过最大载重！')
               this.itemData.weight = 0;
               return
            }
            this.itemData.countQuantity = this.itemData.weight
            this.itemData.countCarriage = this.itemData.countPrice * this.itemData.weight
          }
        } else if (this.itemData.shipByPackOrqty === 'qty') {
          if (this.itemData.quantity) {
            this.itemData.countQuantity = this.itemData.quantity
            this.itemData.countCarriage = this.itemData.countPrice * this.itemData.quantity
          }
        } else if (this.itemData.shipByPackOrqty === 'pack') {
          if (this.itemData.packQty) {
            this.itemData.countQuantity = this.itemData.packQty
            this.itemData.countCarriage = this.itemData.countPrice * this.itemData.packQty
          }
        } else {
          if (this.itemData.volume) {
            if (this.itemData.volume > this.data.maxVol) {
               this.$message.warning('超过最大体积！')
                this.itemData.volume = 0;
               return
            }
            this.itemData.countQuantity = this.itemData.volume
            this.itemData.countCarriage = this.itemData.countPrice * this.itemData.volume
          }
        }
        this.itemData.amountExpense = this.itemData.countCarriage
      } else {
        this.itemData.countCarriage = 0
      }
    },
    handleCalMaterialValue() {
      if (this.itemData.unitPrice) {
        if (this.itemData.weight) {
          this.itemData.cargoValue = this.itemData.unitPrice * this.itemData.weight
        }

        this.handleCalInsuranceExpense()
      } else {
        this.itemData.materialValue = 0
      }
    },
    handleCalInsuranceExpense() {
      if (this.itemData.materialValue && this.itemData.insuranceFeeRate) {
        this.itemData.insuranceExpense = this.itemData.materialValue * this.itemData.insuranceFeeRate
      } else {
        this.itemData.insuranceExpense = 0
      }
    },
    handleLocationChange() {
      // 先清空里程
      this.data.miles = undefined
      if (this.data.departureIdList.length !== 0 && this.data.destinationIdList.length !== 0) {
        // 根据起始地和目的地，查询线路信息
        const params = {
          startLocation: this.data.departureIdList.join(','),
          endLocation: this.data.destinationIdList.join(',')
        }
        TransitRouteApi.list(params).then(response => {
          if (response.data.length > 0) {
            // 设置里程
            this.data.miles = response.data[0].milometer
            this.data.estDeliveryDays = response.data[0].estDeliveryDays
          }
        })
      }
    },
    openVehicleModelSelector() {
      this.vehicleModelSelectorVisible = true
    },
    handleVehicleModelSelected(obj) {
      this.data.vehicleModelNo = obj.id
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
</style>
